<template>
  <el-dialog :title="tipText" center :before-close="handleCancel" :visible.sync="visible" width="500px" :close-on-click-modal="false" :show-close="true" append-to-body>
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-row>
        <el-col :span="24">
          <el-form-item prop="oldPassword" style="margin-bottom:44px">
            <template slot="label">原密码</template>
            <el-input v-model="form.oldPassword" placeholder="请输入原密码" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="password" style="margin-bottom:44px">
            <template slot="label">新密码</template>
            <el-input v-model="form.password" show-password placeholder="请输入新密码" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="确认密码" prop="passwordCheck">
            <el-input v-model="form.passwordCheck" show-password placeholder="请确认新密码" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="loading" @click="submitForm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { mapState, mapActions } from "vuex";
import { changeCurrentPassWord } from '../../../api/system/person/api';
import { isCheckPosswordStrength } from "../../../utils/validate";
import { getInfo } from '../../../api/login';
import pinyin from '../../../utils/pinyin';
export default {
  name: "ResetPwModal",
  data()
  {
    let validatePass2 = (rule, value, callback) =>
    {
      if (value === '')
      {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.form.password)
      {
        callback(new Error('两次输入密码不一致!'));
      } else
      {
        callback();
      }
    };

    let validatePass = (rule, value, callback) => 
    {
      if (value === '')
      {
        callback(new Error('请输入密码'));
      }
      else 
      {
        let checkReturnObj = isCheckPosswordStrength(value, this.DICT_PASSWORD_STRENDTH, this.notAllowKey);
        if (checkReturnObj.isOk)
        {
          callback();
        }
        else
        {
          callback(new Error(checkReturnObj.msg));
        }
      }
    }
    return {
      loading: false,
      visible: false,
      promiseStatus: {},
      //不允许包含的关键字符串
      notAllowKey: [],
      form: {},
      tipText: "",
      rules: {
        oldPassword: [
          { required: true, message: "请输入原密码", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: validatePass, trigger: 'blur' }
        ],
        passwordCheck: [
          { required: true, message: "请再次输入密码", trigger: "blur" },
          { validator: validatePass2, trigger: 'blur' }
        ],
      }
    }

  },
  computed: {
    ...mapState("dict", ["DICT_PASSWORD_STRENDTH"]),
  },
  created()
  {
    //获取办理方式列表
    this.getCs({
      dictKey: "DICT_PASSWORD_STRENDTH",
      code: "xtsz_password_strendth"
    })
  },
  methods: {
    ...mapActions("dict", ["getCs"]),
    ...mapActions("user", ["LogOut"]),
    //处理取消事件
    handleCancel(){
      this.visible = false;
      //移除token
      this.LogOut();
      this.promiseStatus.reject();
    },
    // 表单重置
    reset()
    {
      this.form = {
        oldPassword: null,
        password: null,
        passwordCheck: null
      };
      console.log(this.form);
      this.resetForm("form");
    },
    show(P_IsDefaultPassword, P_IsOkPasswordStrength, P_IsPasswordExpire)
    {
      if (P_IsDefaultPassword)
      {
        this.tipText = "您使用的是默认密码，请修改后重新登录";
      }
      else if (!P_IsOkPasswordStrength)
      {
        this.tipText = "您使用的密码不符合密码规则，请修改后重新登录";
      }
      else if (P_IsPasswordExpire && P_IsPasswordExpire > 0)
      {
        this.tipText = "您使用的密码已经" + P_IsPasswordExpire + "天未修改了,请修改后重新登录";
      }
      this.reset();
      this.notAllowKey = this.getNotAllowKey();
      this.visible = true;
      
      // 创建promise
      return new Promise((resolve, reject) => {
        this.promiseStatus = {
          resolve,
          reject,
        };
      });
    },
    getNotAllowKey()
    {
      getInfo().then(res =>
      {
        let userInfo = res.result || {};
        let valueToReturn = [];
        valueToReturn.push(userInfo.shortname);
        //全拼
        valueToReturn.push(pinyin.chineseToPinYin(userInfo.personCommonname));
        //首字母
        valueToReturn.push(pinyin.chineseToPY(userInfo.personCommonname));
        //手机号
        if(userInfo.phonenumber && userInfo.phonenumber != "")
        {
          valueToReturn.push(userInfo.phonenumber);
        }
        this.notAllowKey = valueToReturn;
      })
    },
    submitForm()
    {
      this.$refs["form"].validate(valid =>
      {
        if (valid)
        {
          changeCurrentPassWord(this.form).then(res =>
          {
            this.$message.success('密码重置成功')
            this.$emit("reload");
            this.visible = false;
            this.promiseStatus.resolve();
          }).finally(() => { this.loading = false });
        }
      })
    },
    handleBeforeUnload()
    {
      console.log("-----触发销毁---------")
      if (this.visible)
      {
        //移除token
        this.LogOut();
      }
    }
  },
  mounted()
  {
    window.addEventListener('beforeunload', this.handleBeforeUnload);
  },
  beforeDestroy()
  {
    window.removeEventListener('beforeunload', this.handleBeforeUnload);
  }
}
</script>